#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/8 17:01
# @Author  : lizhen
# @Site    : 
# @File    : context.py
# @Software: PyCharm
from contextlib import contextmanager


def open_file():
    f = open('../MySQL.sql', 'r', encoding='utf-8')
    try:
        print(f.read())
    except Exception as e:
        print(e)
    finally:
        f.close()


class CustomContext:
    def __init__(self, file=None, mode=None, encoding=None):
        self.file = file
        self.mode = mode
        self.encoding = encoding

    def __enter__(self):
        print('enter')
        self.fd = open(self.file, self.mode, encoding=self.encoding)
        return self.fd

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit')
        self.fd.close()

    @classmethod
    def run(cls):
        with cls('../MySQL.sql', 'r', encoding='utf-8') as file:
            print(file.read())


class DecoratorContext:
    def __init__(self, file=None, mode=None, encoding=None):
        self.file = file
        self.mode = mode
        self.encoding = encoding

    @contextmanager
    def decorator_open_file(self):
        print('enter')
        f = open(self.file, self.mode, encoding=self.encoding)
        try:
            yield f
        finally:
            print('exit')
            f.close()

    @classmethod
    def run(cls):
        f = cls('../MySQL.sql', 'r', encoding='utf-8')
        with f.decorator_open_file() as file:
            print(file.read())


def main():
    # open_file()
    # cc = CustomContext()
    # cc.run()
    dc = DecoratorContext()
    dc.run()


if __name__ == '__main__':
    main()
